//Given a triangle array, return the minimum path sum from top to bottom. 
//
// For each step, you may move to an adjacent number of the row below. More form
//ally, if you are on index i on the current row, you may move to either index i o
//r index i + 1 on the next row. 
//
// 
// Example 1: 
//
// 
//Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
//Output: 11
//Explanation: The triangle looks like:
//   2
//  3 4
// 6 5 7
//4 1 8 3
//The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined abov
//e).
// 
//
// Example 2: 
//
// 
//Input: triangle = [[-10]]
//Output: -10
// 
//
// 
// Constraints: 
//
// 
// 1 <= triangle.length <= 200 
// triangle[0].length == 1 
// triangle[i].length == triangle[i - 1].length + 1 
// -104 <= triangle[i][j] <= 104 
// 
//
// 
//Follow up: Could you do this using only O(n) extra space, where n is the total
// number of rows in the triangle? Related Topics 数组 动态规划 
// 👍 770 👎 0


package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Java：Triangle
class P120Triangle {
    public static void main(String[] args) {
        Solution solution = new P120Triangle().new Solution();
        // TO TEST
        List<Integer> l1 = new ArrayList<>(Arrays.asList(new Integer[]{2}));
        List<Integer> l2 = new ArrayList<>(Arrays.asList(new Integer[]{3, 4}));
        List<Integer> l3 = new ArrayList<>(Arrays.asList(new Integer[]{6, 5, 7}));
        List<Integer> l4 = new ArrayList<>(Arrays.asList(new Integer[]{4, 1, 8, 3}));
        List<List<Integer>> result = new ArrayList<>();
        result.add(l1);
        result.add(l2);
        result.add(l3);
        result.add(l4);
        System.out.println(solution.minimumTotal(result));

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int minimumTotal(List<List<Integer>> triangle) {
            int sum = Integer.MAX_VALUE;
            if (triangle.size() == 1) {
                return triangle.get(0).get(0);
            }
            for (int i = 1; i < triangle.size(); i++) {
                List<Integer> integers = triangle.get(i);
                for (int j = 0; j < integers.size(); j++) {
                    int min = Integer.MAX_VALUE;
                    if (triangle.get(i - 1).size() > j) {
                        min = triangle.get(i).get(j) + triangle.get(i - 1).get(j);
                    }
                    if (j > 0) {
                        min = Math.min(min, triangle.get(i).get(j) + triangle.get(i - 1).get(j - 1));
                    }
                    integers.set(j, min);
                    if (i == triangle.size() - 1) {
                        sum = Math.min(min, sum);
                    }

                }
            }
            return sum;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}